import requests
from fake_useragent import UserAgent

from utils.logger import loger

header = {'User-Agent': UserAgent(verify_ssl=False).random,
          'Accept': 'application/json,text/plain,*/*',
          'Accept-Language': 'zh-cn,zh;q=0.5',
          'Accept-Charset': 'GB2312,utf-8;q=0.7,*;q=0.7',
          'Accept-Encoding': 'gzip,deflate,br',
          'Content-Type': 'application/json;charset=UTF-8',
          'Connection': 'keep-alive'}


def get_web(url, params=None, timeout=20, h=None):
    """
    Get请求
    :param h:
    :param url:
    :param params:
    :param timeout:
    :param headers:
    :return:
    """
    if h != None:
        global header
        h = Merge(header, h)

    try:
        s = requests.session()
        s.keep_alive = False  # 关闭多余连接
        response = requests.get(url=url, params=params, timeout=timeout, headers=h)
        response.raise_for_status()
        return response
    except BaseException as e:
        loger.info(e.__str__())
        return None


def post_web(url, params=None, json=None, timeout=5, h=None):
    """
    Post请求
    :param url:
    :param params:
    :param json:
    :param timeout:
    :param headers:
    :return:
    """

    try:
        if h != None:
            global header
            h = Merge(header, h)

        response = requests.post(url=url, data=params, json=json, headers=h, timeout=timeout)
        response.raise_for_status()
        return response.json()
    except BaseException as e:
        loger.info(e)
        return None


def Merge(dict1, dict2):
    """
    合并两个字典
    """
    res = {**dict1, **dict2}
    return res
